package net.xdclass.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.ProductMessage;
import net.xdclass.service.ICartService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@RabbitListener(queues = "${mqconfig.stock_releasecart_queue}")
public class CartStockMQListener {

    @Autowired
    private ICartService cartService;

    @RabbitHandler
    private void releaseCartStockRecord(ProductMessage productMessage, Message message, Channel channel) throws IOException {
        log.info("监听到消息: releaseCartRecord消息内容{}", productMessage);
        long msgTag = message.getMessageProperties().getDeliveryTag();
        boolean flag = cartService.releaseCartProductStock(productMessage);

        try {
            if (flag) {
                //确认消息消费成功
                channel.basicAck(msgTag, false);
            } else {
                log.error("释放购物车商品记录失败 flag=false, {}", productMessage);
                channel.basicReject(msgTag, true);
            }
        } catch (IOException e) {
            log.info("释放购物车商品记录异常: {} msg:{} " ,e, productMessage);
            channel.basicReject(msgTag, true);
        }
    }
}
